import time
import io
from django.http import HttpResponse, StreamingHttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.parsers import MultiPartParser

from .models import HrChatSession, HrChatMessage
from .serializers import HrChatSessionSerializer, HrChatSerializer, HrImageUploadSerializer
from user.models import SysUser


class HrChatView(APIView):
    """企业人事助手流式聊天接口（支持结合图片）"""

    def post(self, request):
        # 1. 验证请求数据
        serializer = HrChatSerializer(data=request.data)
        if not serializer.is_valid():
            raise ValidationError(serializer.errors)

        # 2. 提取参数
        prompt = serializer.validated_data["prompt"]
        user_id = serializer.validated_data["user_id"]
        image_url = request.data.get("image_url", None)  # 获取图片URL

        # 3. 获取用户
        try:
            user = SysUser.objects.get(id=user_id)
        except SysUser.DoesNotExist:
            return HttpResponse("用户不存在", status=400)

        # 4. 创建会话
        session_title = prompt[:50] if prompt else "空会话"
        chat_session = HrChatSession.objects.create(
            user=user,
            title=session_title
        )

        # 5. 保存用户消息
        user_message = HrChatMessage.objects.create(
            session=chat_session,
            sender='user',
            content=prompt
        )

        # 6. 调用Coze服务（这里需要实现或集成Coze服务）
        def stream_generator():
            # 模拟AI响应，实际项目中需要替换为真实的Coze服务调用
            ai_response = []
            start_time = time.time()

            try:
                # 构建发送给Coze的消息内容
                coze_message = prompt
                
                # 如果有图片URL，添加到消息中
                if image_url:
                    # 记录图片信息到日志
                    print(f"处理图片URL: {image_url}")
                    # 在消息中添加图片信息
                    coze_message = f"[用户上传了图片: {image_url}]\n\n{prompt}"
                
                # 模拟流式响应
                response_text = f"收到您的问题：{coze_message}\n\n这是企业人事助手的回答。"
                for char in response_text:
                    time.sleep(0.01)  # 模拟延迟
                    ai_response.append(char)
                    yield char

                # 计算耗时和token（简单估算）
                end_time = time.time()
                response_time = round(end_time - start_time, 2)
                tokens_used = len(''.join(ai_response)) // 4  # 粗略估算

                # 保存AI回复
                if ai_response:
                    HrChatMessage.objects.create(
                        session=chat_session,
                        sender='assistant',
                        content=''.join(ai_response),
                        tokens_used=tokens_used,
                        response_time=response_time
                    )

            except Exception as e:
                # 异常时返回[ERROR]标记，前端会捕获并显示
                yield f"[ERROR]{str(e)}"

        # 7. 返回流式响应
        return StreamingHttpResponse(
            stream_generator(),
            content_type="text/plain; charset=utf-8"
        )


class HrImageUploadView(APIView):
    """企业人事助手图片上传接口"""
    parser_classes = [MultiPartParser]  # 支持接收 multipart/form-data 格式文件
    # 限制文件大小：5MB
    MAX_FILE_SIZE = 5 * 1024 * 1024  # 5MB

    def post(self, request):
        # 1. 用序列化器验证图片是否存在
        serializer = HrImageUploadSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)  # 验证失败会自动返回400错误
        image_obj = serializer.validated_data['image']
        user_id = serializer.validated_data.get('user_id', '123456789')

        # 2. 校验文件大小
        if image_obj.size > self.MAX_FILE_SIZE:
            return Response(
                {"detail": f"图片过大（{image_obj.size/1024/1024:.2f}MB），仅支持5MB以内的图片"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 3. 校验文件类型（后缀）
        file_name = image_obj.name
        file_ext = file_name.split('.')[-1].lower() if '.' in file_name else ''   
        valid_exts = ['jpg', 'jpeg', 'png', 'gif']
        if file_ext not in valid_exts:
            return Response(
                {"detail": f"不支持的图片格式（{file_ext}），仅支持JPG、JPEG、PNG、GIF"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 4. 保存图片（实际项目中可能需要保存到云存储）
        try:
            # 获取用户
            try:
                user = SysUser.objects.get(id=user_id)
            except SysUser.DoesNotExist:
                # 如果用户不存在，使用默认用户或创建一个临时用户
                # 这里简化处理，使用ID为1的用户作为默认用户
                try:
                    user = SysUser.objects.get(id=1)
                except SysUser.DoesNotExist:
                    return Response(
                        {"detail": "系统错误：无法找到有效用户"},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR
                    )

            # 创建会话
            session_title = f"图片上传：{file_name}"
            chat_session = HrChatSession.objects.create(
                user=user,
                title=session_title
            )

            # 保存用户消息（包含图片）
            user_message = HrChatMessage.objects.create(
                session=chat_session,
                sender='user',
                content=f"上传了图片：{file_name}",
                image=image_obj
            )

            # 构建完整的图片URL
            image_url = request.build_absolute_uri(user_message.image.url) if user_message.image else None

            # 返回图片信息和会话ID
            return Response({
                "detail": "图片上传成功",
                "session_id": chat_session.id,
                "image_url": image_url,
                "filename": file_name
            }, status=status.HTTP_201_CREATED)

        except Exception as e:
            return Response(
                {"detail": f"图片上传失败：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
        except Exception as e:
            return Response(
                {"detail": f"图片上传失败：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


class HrChatHistoryView(APIView):
    """获取用户的企业人事助手会话历史记录"""

    def get(self, request):
        # 获取用户ID（实际项目中建议从认证系统获取）
        user_id = request.query_params.get('user_id')
        if not user_id:
            return Response(
                {"detail": "缺少user_id参数"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 查询用户的所有会话（按更新时间倒序）
        try:
            user = SysUser.objects.get(id=user_id)
            sessions = HrChatSession.objects.filter(user=user).order_by('-updated_at')

            # 序列化并返回数据
            serializer = HrChatSessionSerializer(sessions, many=True)
            return Response(serializer.data)

        except SysUser.DoesNotExist:
            return Response(
                {"detail": "用户不存在"},
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            return Response(
                {"detail": f"获取历史记录失败：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def post(self, request):
        """保存新的对话会话"""
        try:
            user_id = request.data.get('user_id')
            title = request.data.get('title', '未命名人事咨询')
            messages = request.data.get('messages', [])

            if not user_id:
                return Response(
                    {"detail": "缺少user_id参数"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 获取用户
            user = SysUser.objects.get(id=user_id)

            # 创建会话
            session = HrChatSession.objects.create(
                user=user,
                title=title
            )

            # 保存消息
            for msg_data in messages:
                HrChatMessage.objects.create(
                    session=session,
                    sender=msg_data.get('sender', 'user'),
                    content=msg_data.get('content', ''),
                    tokens_used=msg_data.get('tokens_used', 0),
                    response_time=msg_data.get('response_time', 0.0)
                )

            # 返回创建的会话
            serializer = HrChatSessionSerializer(session)
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        except SysUser.DoesNotExist:
            return Response(
                {"detail": "用户不存在"},
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            return Response(
                {"detail": f"保存会话失败：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def delete(self, request):
        """删除指定的会话"""
        try:
            session_id = request.query_params.get('session_id')
            user_id = request.query_params.get('user_id')

            if not session_id or not user_id:
                return Response(
                    {"detail": "缺少session_id或user_id参数"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 验证用户权限并删除会话
            user = SysUser.objects.get(id=user_id)
            session = HrChatSession.objects.get(id=session_id, user=user)
            session.delete()

            return Response({"detail": "会话删除成功"}, status=status.HTTP_200_OK)

        except SysUser.DoesNotExist:
            return Response(
                {"detail": "用户不存在"},
                status=status.HTTP_404_NOT_FOUND
            )
        except HrChatSession.DoesNotExist:
            return Response(
                {"detail": "会话不存在或无权限"},
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            return Response(
                {"detail": f"删除会话失败：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )